package com.woniuxy.hrp.security;




import com.woniuxy.hrp.exception.ValidateException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用于校验用户携带的jwt是否合法，该过滤器交给security
 */
@Slf4j
public class JwtVerifyFilter extends AbstractAuthenticationProcessingFilter {
    protected JwtVerifyFilter(String defaultFilterProcessesUrl) {
        super(defaultFilterProcessesUrl);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.debug("进入JwtVerifyFilter");
        String jwt = request.getHeader("jwt");
        log.debug("JWT:{}", jwt);
        JwtToken jwtToken = new JwtToken(jwt);
        return this.getAuthenticationManager().authenticate(jwtToken);

    }
    //不调用父类的dofilter，原因是其后续处理直接跳转到首页，但是我们此处是用于前后端分离不用跳转只需放行
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        attemptAuthentication((HttpServletRequest) request, (HttpServletResponse) response);
            chain.doFilter(request, response);
       }

}

